package com.mrobuy.jdvc.controller;

import com.mrobuy.jdvc.Result;
import com.mrobuy.jdvc.dao.TaskDao;
import com.mrobuy.jdvc.entity.Task;
import com.mrobuy.jdvc.entity.VCShelvesTask;
import com.mrobuy.jdvc.model.ItemCondition;
import com.mrobuy.jdvc.service.ShelvesService;
import com.mrobuy.util.Pagination;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 上架管理
 */
@Controller
public class ShelvesController {

	private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");

	@Autowired
	private ShelvesService shelvesService;

	@Autowired
	private TaskDao taskDao;

	@RequestMapping("shelves/task")
	public String task(Model model) {

		Task condition = new Task();
		condition.setStatus(Task.Status.SUCCESS);
		condition.setType("MYMRO");
		Pagination pagination = taskDao.load(0, Integer.MAX_VALUE, condition);
		model.addAttribute("tasks", pagination.getData());

		return "shelves/task";
	}

	@RequestMapping("shelves/attrsetting")
	public String attrsetting(Model model) {
		return "shelves/attrsetting";
	}


	@RequestMapping("shelves/shelves")
	public String shelves(Model model) {
		return "shelves/shelves";
	}

	@RequestMapping("shelves/items")
	public String items(Model model) {
		return "shelves/items";
	}

	/**
	 * 上架任务查询
	 */
	@RequestMapping("shelves/task/query")
	@ResponseBody
	public Object taskquery(HttpServletRequest request, VCShelvesTask condition) {

		int start = ServletRequestUtils.getIntParameter(request, "start", 1);
		int length = ServletRequestUtils.getIntParameter(request, "length", 100);
		int draw = ServletRequestUtils.getIntParameter(request, "draw", 1);

		Pagination pagination = shelvesService.loadTasks(start, length, condition);

		pagination.setDraw(draw);

		return pagination;
	}

	/**
	 * 上架任务新增
	 */
	@RequestMapping("shelves/task/add")
	@ResponseBody
	public Result add(HttpServletRequest request, VCShelvesTask record) {

		Result result = shelvesService.insert(record);

		return result;
	}



	@RequestMapping("shelves/brandcatesetting")
	public String brandcatesetting(Model model) {
		return "shelves/brandcatesetting";
	}

	/**
	 * 类目品牌映射文件导出
	 */
	@RequestMapping("shelves/brandcatesetting/export")
	@ResponseBody
	public void export(HttpServletRequest request, HttpServletResponse response, VCShelvesTask record) {

		VCShelvesTask task = shelvesService.loadTask(record.getId());

		try {
			response.setContentType("application/vnd.ms-excel");
			String fileName = "类目品牌设置_" + task.getName() + "_" + DATE_FORMAT.format(new Date()) + ".xlsx";
			String userAgent = request.getHeader("User-Agent");
			if(StringUtils.contains(userAgent, "Firefox")){//火狐浏览器
				fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
			}else{//IE，google等其他浏览器
				fileName = URLEncoder.encode(fileName,"UTF8");
			}
			response.setHeader("Content-disposition", "attachment;filename=" + fileName);
			OutputStream ouputStream = response.getOutputStream();
			shelvesService.exportBrandcateMapping(ouputStream, task);
			ouputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 类目品牌映射文件导入
	 */
	@RequestMapping("shelves/brandcatesetting/upload")
	@ResponseBody
	public Result upload(HttpServletRequest request, HttpServletResponse response, VCShelvesTask record) {

		String id = request.getParameter("id");
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		if ( files!=null ) {
			for (MultipartFile file : files) {
				System.out.println(file.getOriginalFilename());

				try {
					shelvesService.importCateBrandMapping(file.getInputStream(), id);
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						file.getInputStream().close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

		return new Result(true);
	}


	/**
	 * 类目品牌映射完成
	 */
	@RequestMapping("shelves/brandcatesetting/next")
	@ResponseBody
	public Result brandcatesettingNext(HttpServletRequest request, HttpServletResponse response, VCShelvesTask record) {

		VCShelvesTask task = shelvesService.loadTask(record.getId());

		if ( "3".equalsIgnoreCase(task.getState()) ) {
			task.setState("4");
			taskDao.update(task);
			return new Result(true);
		}


		return new Result(false, "任务[" + task.getName() + "]状态不正确.");
	}



	/**
	 * 商品属性文件导出
	 */
	@RequestMapping("shelves/attrsetting/export")
	@ResponseBody
	public void attrExport(HttpServletRequest request, HttpServletResponse response, VCShelvesTask record) {

		VCShelvesTask task = shelvesService.loadTask(record.getId());

		try {
			response.setContentType("application/vnd.ms-excel");
			String fileName = "商品属性设置_" + task.getName() + "_" + DATE_FORMAT.format(new Date()) + ".xlsx";
			String userAgent = request.getHeader("User-Agent");
			if(StringUtils.contains(userAgent, "Firefox")){//火狐浏览器
				fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
			}else{//IE，google等其他浏览器
				fileName = URLEncoder.encode(fileName,"UTF8");
			}
			response.setHeader("Content-disposition", "attachment;filename=" + fileName);
			OutputStream ouputStream = response.getOutputStream();
			shelvesService.exportAttrSetting(ouputStream, task);
			ouputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 商品属性文件导入
	 */
	@RequestMapping("shelves/attrsetting/upload")
	@ResponseBody
	public Result attrUpload(HttpServletRequest request, HttpServletResponse response, VCShelvesTask record) {

		String id = request.getParameter("id");
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		if ( files!=null ) {
			for (MultipartFile file : files) {
				System.out.println(file.getOriginalFilename());

				try {
					shelvesService.importAttrSetting(file.getInputStream(), id, file.getOriginalFilename());
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						file.getInputStream().close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

		return new Result(true);
	}

	/**
	 * 设置任务启动上架
	 */
	@RequestMapping("shelves/attrsetting/startpush")
	@ResponseBody
	public Result startpush(HttpServletRequest request, HttpServletResponse response, VCShelvesTask record) {

		VCShelvesTask task = shelvesService.loadTask(record.getId());

		if ( task==null ) {
			return new Result(false, "任务[" + record.getId() + "]未找到.");
		}

		if (Strings.isBlank(task.getAttrfile()) ) {
			return new Result(false, "任务[" + task.getName() + "]属性文件未上传.");
		}

		File attrFile = new File(task.getAttrfile());

		if ( !attrFile.exists() ) {
			return new Result(false, "任务[" + task.getName() + "]属性文件丢失， 请重新上传.");
		}


		if ( !"Y".equalsIgnoreCase(task.getEnable()) ) {
			task.setEnable("Y");
			task.setEnabletime(new Date());
			taskDao.update(task);
			return new Result(true, "启动成功");
		}

		return new Result(false, "任务[" + task.getName() + "]已经启动上架.");
	}

	/**
	 * 设置任务停止上架
	 */
	@RequestMapping("shelves/attrsetting/stoppush")
	@ResponseBody
	public Result stoppush(HttpServletRequest request, HttpServletResponse response, VCShelvesTask record) {

		VCShelvesTask task = shelvesService.loadTask(record.getId());

		if ( "Y".equalsIgnoreCase(task.getEnable()) ) {
			task.setEnable("N");
			task.setEnabletime(null);
			taskDao.update(task);
			return new Result(true, "停止成功");
		}

		return new Result(false, "任务[" + task.getName() + "]还未启动上架.");
	}


	/**
	 * 上架商品查询
	 */
	@RequestMapping("shelves/items/query")
	@ResponseBody
	public Object itemsquery(HttpServletRequest request, ItemCondition condition) {

		int start = ServletRequestUtils.getIntParameter(request, "start", 1);
		int length = ServletRequestUtils.getIntParameter(request, "length", 100);
		int draw = ServletRequestUtils.getIntParameter(request, "draw", 1);

		Pagination pagination = shelvesService.loadItems(start, length, condition);

		pagination.setDraw(draw);

		return pagination;
	}


}
